# -*- coding: utf-8 -*- 
# @project : 《剑指offer》
# @Author : created by bensonrachel on 2021/6/11
# @File : 二进制中1的个数.py

class Solution(object):
    def NumberOf1(self, n):
        """
        :type n: int
        :rtype: int
        """
        if (n == 0): return 0#用原理法
        if (n >= 1):
            rem = 0
            while (n != 0):
                if (n % 2 == 1): rem += 1#每次取余再除以2，即可得到二进制的逆序。
                n = n // 2
            return rem
        if (n < 0):
            n = -n
            tag = 0
            rem = 0
            w = 0
            a = 0
            while (n != 0):
                if (n % 2 == 1):
                    if (a == 0):
                        w = tag + 1
                        a = 1
                    rem += 1
                n = n // 2
                tag += 1
            b = 32 - w - (rem - 1) + 1#脑海里原码转补码的小技巧
            return b
if __name__ == '__main__':
    a =Solution()
    b = a.NumberOf1(-732)
    print(b)